import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import store from '@/store'
import { getPermission } from '@/api'
export const dynamicRoutes: Array<RouteRecordRaw> = [{
  path: '/home',
  name: 'home',
  meta: {
    title: '首页',
    role: 'user'
  },
  component: () => import(/* webpackChunkName: "home" */ '@/views/home/index.vue')
}, {
  path: '/list',
  name: 'list',
  meta: {
    title: '列表管理',
    role: 'admin'
  },
  component: () => import(/* webpackChunkName: "list" */ '@/views/list/index.vue'),
},{
  path: '/add',
  name: 'add',
  meta: {
    title: '添加列表',
    role: 'admin'
  },
  component: () => import(/* webpackChunkName: "add" */ '@/views/add/index.vue'),
}]

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'layout',
    component: () => import(/* webpackChunkName: "about" */ '@/views/layout/index.vue'),
  },
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "login" */'@/views/login/index.vue')
  }, {
    path: '/',
    redirect: '/home'
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})


// 路由拦截
router.beforeEach(async (to, from, next) => {
  // 令牌
  const token = localStorage.getItem('token');
  // 白名单（不需要登录权限）
  const whiteList = ['/login', '/regist']
  // 获取动态路由表 
  const routes = store.state.routes

  if (token) {
    // 已登录
    // 查看是否已经生成动态路由表
    if (routes.length) {
      // 存在动态路由
      await next()
    } else {
      // 不存在动态路由
      // 获取用户权限
      const resp = await getPermission({ token })
      const { roles } = resp.data
      // 动态设置路由表
      store.dispatch('setRoutes', roles)
      // 重新跳转一下
      await next({ ...to, replace: true })
    }
  } else {
    // 未登录
    if (whiteList.includes(to.path)) {
      await next()
    } else {
      await next({ name: 'login' })
    }
  }
})

export default router
